#!/usr/bin/env python3
"""
运行工作正常的插件系统测试

只运行已经验证可以通过的测试文件。
"""

import sys
import subprocess
from pathlib import Path


def run_working_tests():
    """运行工作正常的测试"""
    
    # 已验证可以通过的测试文件
    working_tests = [
        "test_plugin_base.py",
        "test_plugin_exceptions_simple.py",
        "test_plugin_hooks_simple.py",
        "test_plugin_manager_actual.py",
        "test_plugin_registry_simple.py",
        "test_plugin_context_simple.py",
        "test_plugin_integration_simple.py"
    ]
    
    print("🧪 运行插件系统工作测试...")
    print("=" * 60)
    
    total_passed = 0
    total_failed = 0
    
    for test_file in working_tests:
        print(f"\n📋 运行 {test_file}...")
        print("-" * 40)
        
        cmd = ["python", "-m", "pytest", test_file, "-v", "--tb=short"]
        
        result = subprocess.run(cmd, cwd=Path(__file__).parent, capture_output=True, text=True)
        
        if result.returncode == 0:
            print(f"✅ {test_file} - 所有测试通过")
            # 从输出中提取通过的测试数量
            lines = result.stdout.split('\n')
            for line in lines:
                if 'passed' in line and '=' in line:
                    try:
                        passed = int(line.split()[0])
                        total_passed += passed
                        print(f"   通过: {passed} 个测试")
                    except:
                        pass
        else:
            print(f"❌ {test_file} - 有测试失败")
            print("错误输出:")
            print(result.stdout)
            if result.stderr:
                print("标准错误:")
                print(result.stderr)
            total_failed += 1
    
    print("\n" + "=" * 60)
    print("📊 测试结果总结")
    print("=" * 60)
    print(f"✅ 通过的测试: {total_passed}")
    print(f"❌ 失败的测试文件: {total_failed}")
    print(f"📁 测试文件总数: {len(working_tests)}")
    
    if total_failed == 0:
        print("\n🎉 所有测试文件都通过了！")
        return True
    else:
        print(f"\n⚠️  有 {total_failed} 个测试文件失败")
        return False


def run_coverage_report():
    """运行覆盖率报告"""
    
    working_tests = [
        "test_plugin_base.py",
        "test_plugin_exceptions_simple.py",
        "test_plugin_hooks_simple.py",
        "test_plugin_manager_actual.py",
        "test_plugin_registry_simple.py",
        "test_plugin_context_simple.py",
        "test_plugin_integration_simple.py"
    ]
    
    print("\n📊 生成覆盖率报告...")
    print("=" * 60)
    
    cmd = [
        "python", "-m", "pytest",
        "--cov=src.core.plugin",
        "--cov-report=term-missing",
        "--cov-report=html:htmlcov_working",
    ] + working_tests
    
    result = subprocess.run(cmd, cwd=Path(__file__).parent)
    
    if result.returncode == 0:
        print("\n✅ 覆盖率报告生成成功")
        print("HTML报告位置: htmlcov_working/index.html")
    else:
        print("\n❌ 覆盖率报告生成失败")
    
    return result.returncode == 0


def run_specific_test(test_file, test_class=None, test_method=None):
    """运行特定测试"""
    
    cmd = ["python", "-m", "pytest", "-v"]
    
    if test_class and test_method:
        test_target = f"{test_file}::{test_class}::{test_method}"
    elif test_class:
        test_target = f"{test_file}::{test_class}"
    else:
        test_target = test_file
    
    cmd.append(test_target)
    
    print(f"🔍 运行特定测试: {test_target}")
    print("=" * 60)
    
    result = subprocess.run(cmd, cwd=Path(__file__).parent)
    return result.returncode == 0


def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="运行插件系统工作测试")
    
    parser.add_argument(
        "--coverage", "-c",
        action="store_true",
        help="生成覆盖率报告"
    )
    
    parser.add_argument(
        "--file", "-f",
        help="运行特定测试文件"
    )
    
    parser.add_argument(
        "--class", "-C",
        dest="test_class",
        help="运行特定测试类"
    )
    
    parser.add_argument(
        "--method", "-m",
        dest="test_method",
        help="运行特定测试方法"
    )
    
    args = parser.parse_args()
    
    # 运行特定测试
    if args.file:
        success = run_specific_test(args.file, args.test_class, args.test_method)
        return 0 if success else 1
    
    # 运行所有工作测试
    success = run_working_tests()
    
    # 生成覆盖率报告
    if args.coverage and success:
        run_coverage_report()
    
    return 0 if success else 1


if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)
